package com.eece496.Server;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.io.File;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.eece496.Database.Enrollment;
import com.eece496.Database.Student;

/**
 * Servlet implementation class ProfAddClassServlet
 */
public class ProfAddClassServlet extends MasterServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ProfAddClassServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Connect();
		String courseNumber = null;
		String sectionNumber=  null;
		String firstname = null;
		String lastname = null;
		String isError = "false";
		
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		//System.out.println(isMultipart);

		if (isMultipart) {
			// Create a factory for disk-based file items
			FileItemFactory factory = new DiskFileItemFactory();
			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);
			// Create a new file upload handler
			
			try {
				List <FileItem> items = upload.parseRequest(request);
				
				
				if (!items.get(0).isFormField()) {
					String fileName = items.get(0).getName();
					String root = getServletContext().getRealPath("/");
					File path = new File(root + "/uploads");
					if (!path.exists()) {
						boolean status = path.mkdirs();
					}

					courseNumber = items.get(1).getString();
			        sectionNumber = items.get(2).getString();
			        firstname = items.get(3).getString();
			        lastname = items.get(4).getString();
					System.out.println(courseNumber);
					System.out.println(sectionNumber);
					System.out.println(firstname);
					System.out.println(lastname);
					
					File uploadedFile = new File(path + "/" + fileName);
					System.out.println(uploadedFile.getAbsolutePath());
					
					items.get(0).write(uploadedFile);
				

					BufferedReader input = new BufferedReader(new FileReader(
							uploadedFile));
					StringTokenizer st = null;
					
					ArrayList<ArrayList<String>> List = new ArrayList<ArrayList<String>>();
					String line;
					
					while ((line = input.readLine()) != null) {
						//System.out.println(line);
						
						st = new StringTokenizer(
								line, ",");
						ArrayList<String> studentInfo = new ArrayList<String>();
						while (st.hasMoreTokens()) {
							studentInfo.add(st.nextToken());
						}
						List.add(studentInfo);
					}

				for(ArrayList<String> str: List)
				{
					//ignore the 1st list
					if(str == List.get(0))
						continue;
					
					int studentID = Integer.parseInt(str.get(0)); 
					String userName = str.get(1);
					String password = str.get(2); //Will Remove
					String firstName = str.get(3);
					String lastName = str.get(4);
					String email = str.get(5);
					String program = str.get(6);
					int year = Integer.parseInt(str.get(7));
					int GPA = Integer.parseInt(str.get(8));
					
					//Add students to the database
					Student StudentDB = new Student(studentID, userName,password,firstName,lastName,email,program,year,GPA);
					StudentDB.Setup(connection);
					
				//	System.out.println(StudentDB.UserExists(studentID));
					if(StudentDB.UserExists(studentID) == false)
					{
						StudentDB.Insert();
					}
					
					//Enroll Students to the Course
					Enrollment EnrollmentDB = new Enrollment(studentID, courseNumber,sectionNumber);
					
					EnrollmentDB.Setup(connection);
					EnrollmentDB.Insert();	
				}
				
				request.setAttribute("firstname", firstname);
				request.setAttribute("lastname", lastname);
				request.setAttribute("courseNumber", courseNumber);
				request.setAttribute("sectionNumber", sectionNumber);
				request.getRequestDispatcher("/Professor/Professor-Course-Portal.jsp")
						.forward(request, response);
				
				}
				// Process the input stream
			} catch (FileUploadException e) {
				isError = "true";
				request.setAttribute("isError", isError);
				request.setAttribute("firstname", firstname);
				request.setAttribute("lastname", lastname);
				request.setAttribute("courseNumber", courseNumber);
				request.setAttribute("sectionNumber", sectionNumber);
				request.getRequestDispatcher("/Professor/Professor-Add-Class-List.jsp")
				.forward(request, response);
				e.printStackTrace();
			} catch (Exception e) {
				isError = "true";
				request.setAttribute("isError", isError);
				request.setAttribute("firstname", firstname);
				request.setAttribute("lastname", lastname);
				request.setAttribute("courseNumber", courseNumber);
				request.setAttribute("sectionNumber", sectionNumber);
				request.getRequestDispatcher("/Professor/Professor-Add-Class-List.jsp")
				.forward(request, response);
				e.printStackTrace();
			}
		}

	}

}
